package com.app.util;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

@SuppressWarnings({"unchecked","unused"})
public class Dom4jUtil {

	public static void main(String[] args){
//		getXMLObject("e:/172.27.0.10-1552.xml");
		writer("e:/t.xml");
	}
	
	/*********************
	 * 将xml字符串转换成map对象
	 * @param text
	 * @return
	 */
	public static List<Map> getXMLObject(String file){
		SAXReader reader = new SAXReader();
		
		List<Map> reList = new ArrayList<Map>();
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
			Element b = root.element("cmData");
			List<Element> list = b.elements("managedObject");
			
			for (Element e : list) {
				List<Element> dd = e.elements("p");
				Map objMap = new HashMap<String,String>();
				for(Element ee : dd){
					//System.out.println(ee.attribute("name").getValue()+":"+ee.attribute("value").getValue());
					System.out.println(ee.attribute("name").getValue()+","+ee.getText());
				}
				reList.add(objMap);
				List<Element> ddList = e.elements("list");
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return reList;
	}
	public static void writer(String file){
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileWriter(file),format);
			
			Document document = DocumentHelper.createDocument();
			Element root = document.addElement("root");
			
			boolean b = root.hasContent();
			b=root.isTextOnly();
			
			Element list = root.addElement("list");
			Element p = list.addElement("p");
			p.addAttribute("a1", "v1");
			
			b = p.hasContent();
			b=p.isTextOnly();
			
			p = list.addElement("p");
			p.addAttribute("a2", new String("aa".getBytes("utf8"),"gbk"));
			p.setText("p2");
			
			b = p.hasContent();
			b=p.isTextOnly();
			
			p = list.addElement("p");
			p.setText("p3");
			
			b = p.hasContent();
			b=p.isTextOnly();
			
			p = list.addElement("p");
			
			b = p.hasContent();
			b=p.isTextOnly();
			
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
